package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CommentHotServiceImpl implements CommentHotService {

    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 热点文章查询
     * @param entryId
     * @param apComment
     */
    @Override
    @Async("taskExecutor")
    public void hotCommentExecutor(Long entryId, ApComment apComment) {
        //查询热门评论，按照点赞数量降序排列
        Query query = Query.query(Criteria.where("flag").is((short) 1))
                .with(Sort.by(Sort.Direction.DESC, "likes"));
        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);
        //判断热门评论数量
        if(apCommentList==null||apCommentList.size()<5){
            apComment.setFlag((short)1);
            mongoTemplate.save(apComment);
            return;
        }
        //获取热门评论最后一名
        ApComment lastApComment = apCommentList.get(apCommentList.size() - 1);
        //比较点赞数量
        if(lastApComment.getLikes()>apComment.getLikes()){
            //保持原样
            return;
        }
        //更改热门
        apComment.setFlag((short)1);
        mongoTemplate.save(apComment);
        lastApComment.setFlag((short)0);
        mongoTemplate.save(lastApComment);
    }
}
